package com.springboot.controller;

import com.google.common.util.concurrent.RateLimiter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: luobendexiaoqiang
 * @Date: 2020/7/28 17:17
 */
@RestController
public class RateLimiterController {

    private static volatile AtomicInteger atomicInteger = new AtomicInteger();
    private static long startTime = 0;

    public static ConcurrentHashMap<String, RateLimiter> resourceRateLimiter = new ConcurrentHashMap<>();

    @PostConstruct
    public void setRate() {
        // 每秒100个令牌
        RateLimiter rateLimiter = RateLimiter.create(100.0);
        resourceRateLimiter.put("order", rateLimiter);
    }


    @GetMapping("/test/rate")
    public void testRate() {
        if (atomicInteger.get() == 0) {
            startTime = System.currentTimeMillis();
            System.out.println("开始时间" + startTime);
        }
        atomicInteger.incrementAndGet();
        RateLimiter rateLimiter = resourceRateLimiter.get("order");
        // 获取令牌
        boolean flag = rateLimiter.tryAcquire();
        //获取到令牌,执行业务逻辑
        if (flag) {
            System.out.println("执行业务逻辑");
            //没获取到令牌, 限流
        } else {
            System.out.println("限流限流");
        }
        if (atomicInteger.get() == 400) {
            System.out.println("消耗时间:" + (System.currentTimeMillis() - startTime) + "ms");
            atomicInteger = new AtomicInteger();
        }
    }


}
